package com.twu.biblioteca;

import java.io.IOException;

public class CheckOuter implements LibraryAction {

    private Library library;
    private String ACTION_NAME = "2 - Checkout A Book";
    private IOManager ioManager;

    public CheckOuter(Library library, IOManager ioManager){
        this.library = library;
        this.ioManager = ioManager;
    }

    @Override
    public void performAction() {
        ioManager.print("What book would you like to check out?");
        String title = getInput();

        LibraryBook book = library.findBook(title);
        checkoutBook(book);
    }

    private void checkoutBook(LibraryBook book) {
        if(book == null){
            checkOutFailure();
        }
        else if (book.tryCheckOut()){
            checkOutSuccess();
        }
        else{
            checkOutFailure();
        }
    }

    private String getInput() {
        String title = "";
        try {
            title = ioManager.getUserInput();
        } catch(IOException ex) {
            ioManager.print("Error reading book title.");
        }
        return title;
    }

    public void checkOutSuccess(){
        ioManager.print("Thank you! Enjoy the book");
    }
    @Override
    public String toString() {
        return ACTION_NAME;
    }

    public void checkOutFailure() {
        ioManager.print("That book is not available");
    }
}
